package org.lyd.spring.restful.advice;

import org.lyd.spring.restful.comom.BizException;
import org.lyd.spring.restful.comom.Result;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author:lyd 自定义全局异常处理类
 **/
//@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public Result handleException(ArithmeticException e) {
        System.out.println("【全局】 - ArithmeticException 处理");
        return Result.error(500, e.getMessage());
    }

    /**
     * 处理业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BizException.class)
    public Result handleBizException(BizException e) {
        System.out.println("【全局】 - BizException 处理");
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidException(MethodArgumentNotValidException e) {
        System.out.println("【全局】 - MethodArgumentNotValidException 处理");
        //获取错误信息
        BindingResult result = e.getBindingResult();
        //获取错误字段
        List<FieldError> fieldError = result.getFieldErrors();
        //封装成map
        Map<String, String> fieldErrorMap = fieldError.stream()
                .collect(Collectors.toMap(
                        FieldError::getField,
                        fieldError2 -> fieldError2.getDefaultMessage()
                ));
        return Result.error(500, "参数错误",fieldErrorMap);
    }
}
